﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
using System.Threading;
using System.Collections;

namespace TrafficControl
{
    public class TrafficSimulation
    {
        System.Timers.Timer timer = new System.Timers.Timer();
        
        TrafficLightManager trafficLightManager = new TrafficLightManager();
        Thread trafficLightManangerThread;

        public Dictionary<Position, Cross> crossCollection = new Dictionary<Position, Cross>();
        public List<Thread> roadThread = new List<Thread>();

        public delegate void trafficSimulationDelegate(Dictionary<Position, Cross> crosses);
        public event trafficSimulationDelegate trafficSimulation;
        

        public Boolean addNewCross(Position position)
        {
            this.crossCollection.Add(position,new Cross(position));
            return true;
        }

        public Boolean removeCross(Position position) {
            return this.crossCollection.Remove(position);
        }

        public Boolean configureSettings(Hashtable properties) {
            return true;
        }

        public void startSimulation() {

            this.initializeCrosses();

            this.initializeRoads();

            this.initializeTrafficLights();

            timer.Start();

            foreach(KeyValuePair<Position ,Cross> item in this.crossCollection)
            {
                for (int i = 0; i < 4; i++)
                {
                    ((Cross)item.Value).threads[i] = new Thread(((Cross)item.Value).roads[i].Run);
                    ((Cross)item.Value).threads[i].IsBackground = true;
                    ((Cross)item.Value).threads[i].Start();
                }
                
            }

            trafficSimulation += new trafficSimulationDelegate(trafficLightManager.adjustTrafficLightTime);

            while (true) {
                Thread.Sleep(1000);
                this.trafficSimulation(this.crossCollection);
            }

        }

        public void pauseSimulation() { 
        
        }

        public void resumeSimulation() { 
        
        }


        public Dictionary<Position, Cross> getCrosses()
        {
            return null;
        }

        public ArrayList getTrafficLightStatus() {
            return null;
        }


        public bool setTrafficStream(TrafficStream trafficStream) {
            return true;
        }


        public void initializeCrosses()
        {

        }
        
        public void initializeRoads() { 
        
        }

        public void initializeTrafficLights()
        {

        }


    }
}
